package demo.Socket_learn.ManyTcpClent;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/16-08-16-9:53
 * @Description：demo.Socket_learn.Socket_talk   服务端
 */
//服务端接收数据
public class TCP_Server {
    public static void main(String[] args) {
        ServerSocket server = null;
        Socket accept = null;
        PrintWriter writer = null;
        BufferedReader reader1 = null;
        BufferedReader reader2 = null;
        try {
            server = new ServerSocket(6666);
            System.out.println("服务端启动，等待客户端连接，，，，");


            //System.out.flush();
            while(true){      //无限接收客户端
                accept = server.accept();
                System.out.println(accept);
                //接收数据
                //read 是一个阻塞流，等待对方写数据
                writer= new PrintWriter(new OutputStreamWriter(accept.getOutputStream()));
                reader1= new BufferedReader(new InputStreamReader(accept.getInputStream(), "utf-8"));
                reader2 = new BufferedReader(new InputStreamReader(System.in));
                String str;
                while (true){
                    str = reader1.readLine();
                    System.out.println("客户端： " + str);
                    System.out.flush();

                    str = reader2.readLine();

                    //服务端回写数据
                    writer.println(str);
                    writer.flush();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(server != null){
                    server.close();
                }
                if(accept != null){
                    accept.close();
                }
                if(writer != null){
                    writer.close();
                }
                if(reader1 != null){
                    reader1.close();
                }
                if(reader2 != null){
                    reader2.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
